<?php

class Menu extends CActiveRecord {

    public $children;

    public function rules() {
        return array(
            array('menu_name, menu_parent_id', 'required'),
            array('menu_name, menu_link', 'length', 'max' => 250)
        );
    }

    public function attributeLabels() {
        return array(
            'menu_id' => Yii::t('default', '分类编号'),
            'menu_name' => Yii::t('default', '菜单名'),
            'menu_parent_id' => Yii::t('default', '菜单层级'),
            'menu_link' => Yii::t('default', '菜单链接'),
            'menu_sort' => Yii::t('default', '显示顺序')
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{menu}}';
    }

    public function getParentOption() {
        $list = $this->findAll('menu_parent_id=0');
        $result = array();
        $result[0] = Yii::t('menu.selection.empty', '设为栏目名称');
        foreach ($list as $row) {
            $result[$row['menu_id']] = $row['menu_name'];
        }
        return $result;
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                if ($this->menu_sort > 0) {
                    $this->menu_sort = $this->getLastSortByParentId($this->menu_parent_id) + 1;
                }
            }
            return true;
        }
        else
            return false;
    }

    public function getLastSortByParentId($parentId=0) {
        $result = $this->count('menu_parent_id = :id', array(':id' => $parentId));
        return $result;
    }

    public function beforeDelete() {
        if (parent::beforeSave()) {
            
            if ( $this->menu_parent_id<=0 && $this->find("menu_parent_id = " + $this->menu_id)!=null) {
                $this->addError('delete', Yii::t('default', '不能删除此菜单'));
                return false;
            }
            return true;
        }
        else
            return false;
    }

}